package com.hfzy.ihk.common.web.context;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.common.web.LoginParam;
import com.hfzy.ihk.common.web.constants.WebConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *
 * 通过线程保存上下文或透传参数
 *
 * @author
 */
public class WebThreadContextHolder {

    private static final Logger logger = LoggerFactory.getLogger(WebThreadContextHolder.class);

    private static ThreadLocal<HttpServletRequest> request = new ThreadLocal<HttpServletRequest>();

    private static ThreadLocal<HttpServletResponse> response = new ThreadLocal<HttpServletResponse>();

    private static ThreadLocal<Object> synData = new ThreadLocal<Object>();

    private static HttpSession getSession() {
        return getRequest()!=null?getRequest().getSession():null;
    }

    public static HttpServletRequest getRequest() {
        return request.get()!=null?request.get():null;
    }

    public static HttpServletResponse getResponse() {
        return response.get();
    }


    public static <T> void setSynData(T t){
        synData.set(t);
    }
    public static void removeSynData(){
        synData.remove();
    }

    public static <T> T getSynData(Class<T> tClass){
        return (T)synData.get();
    }

    public static void setRequestResponse(HttpServletRequest req,HttpServletResponse resp) {
        request.set(req);
        response.set(resp);
    }

    public static void clearRequestResponse() {
        request.remove();
        response.remove();
    }

    public static void sendRedirect(String url) {
        try {
            getResponse().sendRedirect(url);
        } catch (IOException e) {
          logger.error("异常：",e);
        }
    }


    public static String getContextPath() {
        return getRequest().getContextPath();
    }


    public static String getURL(String relativePath) {
        HttpServletRequest req = getRequest();
        return "http://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath() + "/" + relativePath;
    }


    public static void setRequest(HttpServletRequest req) {
        request.set(req);
    }

    public static User getUser(){
        try {
            if (StringTools.isNotempty(getSession())) {
                JSONObject jsonObject = (JSONObject)getSession().getAttribute(WebConstant.SESSION_USER);
                if (StringTools.isEmpty(jsonObject)) {
                    return null;
                }

                return JSON.toJavaObject(jsonObject,User.class);
            } else {
                return null;
            }
        }catch (Exception e){
            logger.error("获取 session user json 转换失败!",e);
            return null;
        }
    }

    public static LoginParam getLoginParam(){

        try {
            if (StringTools.isNotempty(getSession())) {
                JSONObject jsonObject = (JSONObject)getSession().getAttribute(WebConstant.LOGIN_PARAM);
                if (StringTools.isEmpty(jsonObject)) {
                    return null;
                }

                return JSON.toJavaObject(jsonObject,LoginParam.class);
            } else {
                return null;
            }
        }catch (Exception e){
            logger.error("获取 session loginParam json 转换失败!",e);
            return null;
        }

    }
}
